package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"pceservice/api"
	"pceservice/internal/pce"
	"pceservice/internal/topology"
	"pceservice/pkg/gobgp"
	"pceservice/pkg/gopcep"
)

func main() {
	configPath := flag.String("config", "config/config.yaml", "配置文件路径")
	flag.Parse()

	// 加载配置
	config, err := LoadConfig(*configPath)
	if err != nil {
		log.Fatalf("加载配置失败: %v", err)
	}

	// 初始化GoBGP客户端
	gobgpClient, err := gobgp.NewClient(config.GoBGP)
	if err != nil {
		log.Fatalf("初始化GoBGP客户端失败: %v", err)
	}

	// 初始化拓扑管理器
	topoManager := topology.NewManager()

	// 启动拓扑同步
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		if err := gobgpClient.SyncTopology(ctx, topoManager); err != nil {
			log.Printf("拓扑同步失败: %v", err)
		}
	}()

	// 初始化路径计算引擎
	pathEngine := pce.NewEngine(topoManager)

	// 初始化PCEP客户端
	pcepClient, err := gopcep.NewPCEPClient(config.PCEP)
	if err != nil {
		log.Fatalf("初始化PCEP客户端失败: %v", err)
	}

	// 启动PCEP会话
	go func() {
		if err := pcepClient.Connect(); err != nil {
			log.Printf("PCEP会话启动失败: %v", err)
		}
	}()

	// 初始化API服务器
	apiServer := api.NewServer(config.API, topoManager, pathEngine, pcepClient)

	// 启动API服务器
	go func() {
		log.Printf("API服务器启动在 %s", config.API.Address)
		if err := apiServer.Start(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("API服务器启动失败: %v", err)
		}
	}()

	// 优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("接收到关闭信号，开始优雅关闭...")

	ctxShutdown, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancelShutdown()

	if err := apiServer.Shutdown(ctxShutdown); err != nil {
		log.Printf("API服务器关闭失败: %v", err)
	}

	cancel() // 取消所有上下文操作

	log.Println("服务已优雅关闭")
}

// LoadConfig 加载配置文件
func LoadConfig(path string) (*Config, error) {
	// 配置加载实现略
	return &Config{
		GoBGP: gobgp.Config{
			Address: "127.0.0.1:50051",
		},
		API: api.Config{
			Address: "0.0.0.0:8080",
		},
		PCEP: gopcep.Config{
			Address: "127.0.0.1:4189",
		},
	}, nil
}

// Config 应用配置结构
type Config struct {
	GoBGP gobgp.Config  `yaml:"gobgp"`
	API   api.Config    `yaml:"api"`
	PCEP  gopcep.Config `yaml:"gopcep"`
}
